'use strict';

const Controller = require('egg').Controller;
const jwt=require('jsonwebtoken')
const auth=(token)=>{
 try{
   jwt.verify(token,'zjzj')
   return true
 }catch(err){
   return false
 }
}
class HomeController extends Controller {

  // 登录
  async login() {
    const { ctx } = this;
    const {user,pwd}=ctx.request.body
    const data=await this.app.mysql.get('user',{user,pwd})
    if(data){
      const token=jwt.sign({user,pwd},'zjzj',{expiresIn:'3d'})
       ctx.body={
         code:200,
         token,
         data
       }
    }else{
      ctx.body={
        code:503,
        msg:'账户或密码输入不正确'
      }
    }
  }

  // 注册
  async reg(){
    const { ctx } = this;
    const {formState,data1}=ctx.request.body
    const {user,pwd}=formState
    console.log(user,pwd,data1._value)
    const data=await this.app.mysql.get('user',{user})
    if(data){
      ctx.body={
        code:500,
        msg:'用户已存在'
      }
    }else{

      const res=await this.app.mysql.insert('user',{user:user,pwd:pwd,keyid:1,data:data1._value})
      if(res){
        ctx.body={
          code:200,
          msg:'成功'
        }
      }else{
        ctx.body={
          code:500,
          msg:'注册失败'
        }
      }

    }
  }

  // 用户信息
  async username(){
    const {ctx}=this;
  const {token}=ctx.request.body
  ctx.body={
    code:200,
    user:jwt.verify(token,'zjzj')
  }
    

  }

  //列表数据
  async list(){
    const {ctx}=this
    const data=await this.app.mysql.select('list')
    if(data){
       ctx.body={
         code:200,
         data
       }
    }
  }

  //删除

  async del(){
    const {ctx}=this;
    const {id}=ctx.request.body
    const res=await this.app.mysql.delete('list',{id})
    if(res){
    const data=await this.app.mysql.select('list')

       ctx.body={
         code:200,
         data
       }
    }
  }

}

module.exports = HomeController;
